﻿// StmInstruction.cs
// Store multiple instruction class

using System;


namespace armsim
{
    /// <summary>
    /// This class is for a STM instruction in the Arm Architecture
    /// </summary>
    public class StmInstruction : LoadStoreMultipleInstruction
    {

        /// <summary>
        /// Initializes a new StmInstruction
        /// </summary>
        /// <param name="instruction">the new instruction is encoded from this 32 bit number</param>
        public StmInstruction(uint instruction)
            : base(instruction)
        {

        }

        /// <summary>
        /// Executes the STM instruction
        /// </summary>
        /// <param name="cpu">location where the memory will be loaded to</param>
        public override void Execute(VirtualCPU cpu)
        {

            var startAddress = cpu.Registers.ReadRegistersDuringExecute(VirtualMemory.MapRegNoToRegMem(this.Rn)) - 4;


            for (uint i = 15; i != 0u; --i)
            {
                if (this.RegisterList.RegBoolList[i] == true)
                {
                    cpu.RAM.WriteWord(startAddress, cpu.Registers.ReadWord(VirtualMemory.MapRegNoToRegMem(i)));
                    startAddress -= 4;
                }
            }
            if (this.W == 1u)
            {
                cpu.Registers.WriteWord(VirtualMemory.MapRegNoToRegMem(this.Rn), startAddress + 4);
            }

        }

        /// <summary>
        /// Converts the instruction into its string representation and returns it
        /// </summary>
        /// <param name="cpu">the Central Processing unit</param>
        /// <returns>the assembly</returns>
        public override string ToAssembly(VirtualCPU cpu)
        {
            return String.Format("STMFD {0}", base.ToAssembly(cpu));
        }


    }
}
